package com.vote.services.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.vote.dao.VoteCommentDAO;
import com.vote.dao.VoteUserDAO;
import com.vote.domain.VoteComment;
import com.vote.domain.VoteUser;
import com.vote.model.Comment;
import com.vote.services.CommentService;
import com.vote.utils.ModelTransform;


public class CommentServiceImpl implements CommentService {

    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CommentServiceImpl.class);

    @Autowired
    VoteCommentDAO vcDAO;
    
    @Autowired
    VoteUserDAO vuDAO;
    
    @Override
    public int deleteCommentById(int id) {
        try{
            vcDAO.deleteComment(id);
        }
        catch(Exception e){
            logger.info("delete comment("+id+") by id fail!\n", e);
        }
        return 0;
    }

    @Override
    public List<Comment> getCommentListByQuestionnaireId(int questionnaireId, int offset, int length) {
        List<VoteComment> voteCommentList = null;
        List<Comment> questionnaireList = new ArrayList<Comment>();
        try{
            voteCommentList = vcDAO.getCommentListByQuestionnaireId(questionnaireId, offset, length);
            if(voteCommentList != null){
                Comment comment = null;
                for(VoteComment vc: voteCommentList){
                    comment = ModelTransform.domain2mode(vc);
                    comment.setFromUserName(getUserNameByUserId(vc.getFromUserId()));
                    comment.setToUserName(getUserNameByUserId(vc.getToUserId()));
                    questionnaireList.add(comment);
                }
            }
            else{
                logger.debug("get null comment list by questionnaire id = " + questionnaireId);
            }
        }
        catch(Exception e){
            logger.info("get comment list by questionnaire("+questionnaireId+") fail!\n", e);
        }
        return questionnaireList;
    }

    @Override
    public int insertComment(Comment comment) throws Exception{
        int id = -1;
        try{
            VoteComment vc = ModelTransform.model2domain(comment);
            id = synInsertComment(vc);
        }
        catch(Exception e){
            logger.info("insert comment "+comment.getCommentText()+" fail!\n", e);
        }
        return id;
    }
    
    private String getUserNameByUserId(int id){
        VoteUser voteUser = null;
        try{
            voteUser = vuDAO.getUser(id);
        }
        catch(Exception e){
            logger.info("get user name by user id in CommentServiceImpl fail!\n", e);
            return null;
        }
        return voteUser.getUserName();
    }

    private synchronized int synInsertComment(VoteComment vc){
        vcDAO.insertComment(vc);
        return vcDAO.getLastInsertId();
    }
}
